import { AuditLogService, AuditLogStats } from '@packages/shared';
import { useNavigate } from 'react-router-dom';
import { useState, useEffect, useCallback } from 'react';
import { Text, Button } from 'packages/ui-shared/src/atoms';
import ComprehensiveScoreChart from '../components/ComprehensiveScoreChart';
import { Classroom } from '../mock/classroomData';
import { getDashboardStats, dashboardDataManager } from '../services/dashboardService';
import { Student, mockStudents } from '../mock/studentData';
import { Chart as ChartJS, ArcElement, Tooltip, Legend, CategoryScale, LinearScale, BarElement } from 'chart.js';
import { Pie, Bar } from 'react-chartjs-2';

import { useSession } from '../hooks/useSession';

// 注册chart.js所需的组件
ChartJS.register(ArcElement, Tooltip, Legend, CategoryScale, LinearScale, BarElement);

export default function DashboardPage() {
  const { session } = useSession();
  const [stats, setStats] = useState<AuditLogStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [dashboardStats, setDashboardStats] = useState({
    totalStudents: 0,
    activeStudents: 0,
    totalClassrooms: 0,
    availableClassrooms: 0
  });
  
  // 添加学生数据统计状态
  const [studentStats, setStudentStats] = useState({
    byStatus: {},
    byGender: {},
    byDepartment: {},
    byCollege: {}
  });
  
  const navigate = useNavigate();

  // 处理学生数据统计的函数
  const getStudentStats = () => {
    // 统计学生状态分布
    const statusCount = mockStudents.reduce((acc: Record<string, number>, student) => {
      acc[student.status] = (acc[student.status] || 0) + 1;
      return acc;
    }, {});

    // 统计学生性别分布
    const genderCount = mockStudents.reduce((acc: Record<string, number>, student) => {
      acc[student.gender] = (acc[student.gender] || 0) + 1;
      return acc;
    }, {});

    // 统计学生市场部分布
    const marketingCount = mockStudents.reduce((acc: Record<string, number>, student) => {
      acc[student.marketingDepartment] = (acc[student.marketingDepartment] || 0) + 1;
      return acc;
    }, {});

    // 统计学生学院分布
    const collegeCount = mockStudents.reduce((acc: Record<string, number>, student) => {
      const collegeName = student.college || '未指定';
      acc[collegeName] = (acc[collegeName] || 0) + 1;
      return acc;
    }, {});

    return {
      statusCount,
      genderCount,
      marketingCount,
      collegeCount,
      totalStudents: mockStudents.length,
      activeStudents: mockStudents.filter(s => s.status === '在读').length
    };
  };

  // 为饼图准备数据 (性别分布)
  const prepareGenderPieData = () => {
    const { genderCount } = getStudentStats();
    const labels = Object.keys(genderCount);
    const data = Object.values(genderCount);
    const colors = ['#FF6B6B', '#4ECDC4', '#FFD166'];

    return {
      labels,
      datasets: [
        {
          data,
          backgroundColor: colors,
          borderWidth: 1,
        },
      ],
    };
  };

  // 为柱状图准备数据 (市场部分布)
  const prepareMarketingBarData = () => {
    const { marketingCount } = getStudentStats();
    const labels = Object.keys(marketingCount);
    const data = Object.values(marketingCount);

    return {
      labels,
      datasets: [
        {
          label: '学生数量',
          data,
          backgroundColor: 'rgba(54, 162, 235, 0.6)',
          borderColor: 'rgba(54, 162, 235, 1)',
          borderWidth: 1,
        },
      ],
    };
  };

  // 加载统计数据
  const loadStats = useCallback(async () => {
    if (!session) return;
    
    try {
      // 获取审计日志统计（保留原有功能）
      const statsData = await AuditLogService.getStats(
        session.userRole,
        session.userId
      );
      setStats(statsData);
    } catch (error) {
      console.error('加载统计数据失败:', error);
      // 使用默认数据
      const defaultStats: AuditLogStats = {
        totalLogs: 156,
        loginCount: 45,
        failedLoginCount: 3,
        userActions: 89,
        adminActions: 67,
        recentActivity: [
          {
            id: '1',
            userId: session.userId,
            userName: session.userName,
            userRole: session.userRole,
            action: 'LOGIN',
            description: '用户登录成功',
            ipAddress: '192.168.1.100',
            userAgent: 'Mozilla/5.0...',
            timestamp: Date.now() - 1000 * 60 * 5, // 5分钟前
            success: true
          }
        ]
      };
      setStats(defaultStats);
    }
  }, [session]);

  // 加载仪表板数据
  const loadDashboardData = useCallback(() => {
    try {
      const data = getDashboardStats();
      setDashboardStats({
        totalStudents: data.totalStudents,
        activeStudents: data.activeStudents,
        totalClassrooms: data.totalClassrooms,
        availableClassrooms: data.availableClassrooms
      });
    } catch (error) {
      console.error('加载仪表板数据失败:', error);
    }
  }, []);

  // 计算学生统计数据
  const calculateStudentStats = useCallback(() => {
    try {
      // 从localStorage获取学生数据，如果没有则使用mock数据
      const savedStudents = localStorage.getItem('students');
      const students: Student[] = savedStudents ? JSON.parse(savedStudents) : mockStudents;
      
      // 按状态统计
      const byStatus = students.reduce((acc, student) => {
        acc[student.status] = (acc[student.status] || 0) + 1;
        return acc;
      }, {} as Record<string, number>);
      
      // 按性别统计
      const byGender = students.reduce((acc, student) => {
        acc[student.gender] = (acc[student.gender] || 0) + 1;
        return acc;
      }, {} as Record<string, number>);
      
      // 按市场部统计
      const byDepartment = students.reduce((acc, student) => {
        acc[student.marketingDepartment] = (acc[student.marketingDepartment] || 0) + 1;
        return acc;
      }, {} as Record<string, number>);
      
      // 按学院统计
      const byCollege = students.reduce((acc, student) => {
        acc[student.college || '未知学院'] = (acc[student.college || '未知学院'] || 0) + 1;
        return acc;
      }, {} as Record<string, number>);
      
      setStudentStats({
        byStatus,
        byGender,
        byDepartment,
        byCollege
      });
    } catch (error) {
      console.error('计算学生统计数据失败:', error);
    }
  }, []);

  useEffect(() => {
    loadStats();
    loadDashboardData();
    calculateStudentStats();
    
    // 注册数据变化监听器
    dashboardDataManager.addListener(loadDashboardData);
    
    // 清理函数
    return () => {
      dashboardDataManager.removeListener(loadDashboardData);
    };
  }, [loadStats, loadDashboardData, calculateStudentStats]);

  if (!session) {
    return (
      <div className="p-6">
        <Text className="text-lg text-gray-500">请先登录</Text>
      </div>
    );
  }

  // 准备图表数据
  const genderData = Object.entries(studentStats.byGender).map(([name, value]) => ({
    name,
    value
  }));
  
  const departmentData = Object.entries(studentStats.byDepartment).map(([name, value]) => ({
    name,
    value
  }));
  
  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

  return (
    <div className="p-6">
      {/* 页面头部 */}
      <div className="mb-6">
        <Text className="text-2xl font-bold text-gray-900 mb-2">
          欢迎回来，{session.userName}！
        </Text>
        <Text className="text-gray-600">
          今天是 {new Date().toLocaleDateString('zh-CN', { 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric',
            weekday: 'long'
          })}
        </Text>
      </div>

      {/* 主要统计信息卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div className="bg-white p-6 rounded-lg shadow">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center">
                <Text className="text-white text-sm">👨‍🎓</Text>
              </div>
            </div>
            <div className="ml-4">
              <Text className="text-sm font-medium text-gray-600">学生总人数</Text>
              <Text className="text-lg font-bold text-gray-900">{dashboardStats.totalStudents}</Text>
            </div>
          </div>
        </div>

        <div className="bg-white p-6 rounded-lg shadow">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <div className="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center">
                <Text className="text-white text-sm">👨‍🏫</Text>
              </div>
            </div>
            <div className="ml-4">
              <Text className="text-sm font-medium text-gray-600">在读学生</Text>
              <Text className="text-lg font-bold text-gray-900">{studentStats.byStatus['在读'] || 0}</Text>
            </div>
          </div>
        </div>

        <div className="bg-white p-6 rounded-lg shadow">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <div className="w-8 h-8 bg-yellow-500 rounded-full flex items-center justify-center">
                <Text className="text-white text-sm">🏫</Text>
              </div>
            </div>
            <div className="ml-4">
              <Text className="text-sm font-medium text-gray-600">教室数量</Text>
              <Text className="text-lg font-bold text-gray-900">{dashboardStats.totalClassrooms}</Text>
            </div>
          </div>
        </div>

        <div className="bg-white p-6 rounded-lg shadow">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <div className="w-8 h-8 bg-purple-500 rounded-full flex items-center justify-center">
                <Text className="text-white text-sm">📊</Text>
              </div>
            </div>
            <div className="ml-4">
              <Text className="text-sm font-medium text-gray-600">学院数量</Text>
              <Text className="text-lg font-bold text-gray-900">{Object.keys(studentStats.byCollege).length}</Text>
            </div>
          </div>
        </div>
      </div>

      {/* 学生状态分布卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        {Object.entries(studentStats.byStatus).map(([status, count]) => {
          let bgColor = 'bg-gray-500';
          if (status === '在读') bgColor = 'bg-green-500';
          else if (status === '休学') bgColor = 'bg-yellow-500';
          else if (status === '退学') bgColor = 'bg-red-500';
          else if (status === '毕业') bgColor = 'bg-blue-500';
          
          return (
            <div key={status} className="bg-white p-6 rounded-lg shadow">
              <div className="flex items-center">
                <div className="flex-shrink-0">
                  <div className={`w-8 h-8 ${bgColor} rounded-full flex items-center justify-center`}>
                    <Text className="text-white text-sm">👥</Text>
                  </div>
                </div>
                <div className="ml-4">
                  <Text className="text-sm font-medium text-gray-600">{status}学生</Text>
                  <Text className="text-lg font-bold text-gray-900">{count}</Text>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* 学生数据可视化图表 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        {/* 性别分布饼图 */}
        <div className="bg-white p-6 rounded-lg shadow">
          <Text className="text-lg font-semibold mb-4">学生性别分布</Text>
          <div style={{ height: 300, width: '100%' }}>
            <Pie 
              data={prepareGenderPieData()} 
              options={{
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                  legend: {
                    position: 'bottom'
                  },
                  tooltip: {
                    callbacks: {
                      label: function(context) {
                        const label = context.label || '';
                        const value = context.raw || 0;
                        const total = context.dataset.data.reduce((a: number, b: number) => a + b, 0);
                        const percentage = ((value / total) * 100).toFixed(0);
                        return `${label}: ${value} (${percentage}%)`;
                      }
                    }
                  }
                }
              }}
            />
          </div>
        </div>

        {/* 市场部分布柱状图 */}
        <div className="bg-white p-6 rounded-lg shadow">
          <Text className="text-lg font-semibold mb-4">学生市场部分布</Text>
          <div style={{ height: 300, width: '100%' }}>
            <Bar 
              data={prepareMarketingBarData()}
              options={{
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                  legend: {
                    display: false
                  }
                },
                scales: {
                  y: {
                    beginAtZero: true,
                    ticks: {
                      precision: 0
                    }
                  }
                }
              }}
            />
          </div>
        </div>
      </div>

      {/* 快速操作 */}
      <div className="mt-8 bg-white rounded-lg shadow p-6">
        <Text className="text-lg font-semibold mb-4">快速操作</Text>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Button 
            variant="outline" 
            className="h-20 flex flex-col items-center justify-center hover:bg-blue-50 transition-colors"
            onClick={() => navigate('/app/classrooms')}
          >
            <Text className="text-2xl mb-2">🏫</Text>
            <Text className="text-sm">教室管理</Text>
          </Button>
          <Button 
            variant="outline" 
            className="h-20 flex flex-col items-center justify-center hover:bg-green-50 transition-colors"
            onClick={() => navigate('/app/students')}
          >
            <Text className="text-2xl mb-2">👨‍🎓</Text>
            <Text className="text-sm">学生管理</Text>
          </Button>
          <Button 
            variant="outline" 
            className="h-20 flex flex-col items-center justify-center hover:bg-yellow-50 transition-colors"
            onClick={() => navigate('/app/teachers')}
          >
            <Text className="text-2xl mb-2">👨‍🏫</Text>
            <Text className="text-sm">讲师管理</Text>
          </Button>
          <Button 
            variant="outline" 
            className="h-20 flex flex-col items-center justify-center hover:bg-purple-50 transition-colors"
            onClick={() => navigate('/app/comprehensive-scores')}
          >
            <Text className="text-2xl mb-2">📊</Text>
            <Text className="text-sm">综合积分管理</Text>
          </Button>
        </div>
      </div>
    </div>
  );
}